package com.killer.controller;


import com.killer.annotate.Limit;
import com.killer.enums.ResultCode;
import com.killer.enums.TaskStatus;
import com.killer.es.entity.dto.EsOrderDTO;
import com.killer.es.service.EsOrderService;
import com.killer.es.service.impl.EsOrderServiceImpl;
import com.killer.mq.MessageProducer;
import com.killer.pojo.dto.BOrderDTO;
import com.killer.pojo.dto.MessageDTO;
import com.killer.pojo.entity.Message;
import com.killer.service.MessageService;
import com.killer.service.TaskService;
import com.killer.untils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Timestamp;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

@RestController
public class ExportController {

    @Autowired
    private MessageProducer messageProducer;

    @Autowired
    private MessageService messageService;



    @Autowired
    private EsOrderService esOrderService;


    @Autowired
    private TaskService taskService;

    @Limit(limitNum = 5,name = "export")
    @RequestMapping(value = "/exportExcel",method = RequestMethod.POST)
    public Result exportExcel(@RequestBody BOrderDTO bOrderDTO){
        //创建任务
        Message message = createTask(bOrderDTO);
        //携带搜索条件,发送异步消息
        messageProducer.asyncSendMQMessageSend(message.getId(),bOrderDTO);
        //返回任务id给前端
        return new Result<>(ResultCode.OK.getCode(), ResultCode.OK.getMessage(),message.getId());
    }


    //轮询接口
    @RequestMapping(value = "/getTaskState",method = RequestMethod.POST)
    public Result getTaskState(@RequestBody MessageDTO messageDTO){
        Message message = messageService.getById(messageDTO.getId());
        return taskService.getTaskStatus(message);
    }


    @RequestMapping(value = "/searchOrder",method = RequestMethod.POST)
    public Result searchOrder(@RequestBody EsOrderDTO esOrderDTO){
        Map<String, Object> result = esOrderService.searchOrder(esOrderDTO);
        return new Result(ResultCode.OK.getCode(), ResultCode.OK.getMessage(),result);
    }


    private Message createTask(BOrderDTO bOrderDTO) {
        Message message = new Message();
        Date date = new Date();
        message.setTask_process(0.0);
        message.setTask_startTime(new Timestamp(date.getTime()));
        message.setCreateTime(date);
        message.setUpdateTime(date);
        message.setStatus(TaskStatus.CREATE.getKey());
        //传递查询条件
        message.setMessage_content(bOrderDTO.toString());
        message.setIsAck(0);
        message.setIsConsumer(0);
        message.setRetryTimes(0);
        message.setVersion(1);
        messageService.insertMessage(message);
        return message;
    }

}
